import * as usersService from '../services/users';

export default {
    namespace: 'users',
    state: {
      list: [],
      total: null,
    },
    reducers: {
      save(state, { payload: { data: list, total, page } }) {
        console.log('保存了 state 的变更，接下来将会进入 与 mapStateToProps 绑定了的组件',list);
        return { ...state, list, total, page };
      },
    },
    effects: {
      *fetch({ payload: { page = 1 } }, { call, put }) {
        console.log('执行了 effects 的 fetch');
        const { data, headers } = yield call(usersService.fetch, { page });
        console.log('data:',data);
        yield put({ type: 'save', payload: {
            data,
            total: parseInt( headers['x-total-count'], 10 ),
            page: parseInt( page, 10 ),
          } 
        });
      },
      *del( { payload: id }, { call, put, select }) {
        if(!id) return false;
        console.warn('delete: ',id);
        yield call(usersService.del, id );
        const page = yield select( state => state.users.page );
        yield put({ type: 'fetch', payload: { page }});
      },
    },
    subscriptions: {
      setup({ dispatch, history }) {
        return history.listen(({ pathname, query }) => {
          if (pathname === '/users') {
            console.log('history 变化，派发 dispatch');
            dispatch({ type: 'fetch', payload: query });
          }
        });
      },
    },
  };